﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using DistributeTransaction.DAL;
using DistributeTransaction.Utils;
using log4net;

namespace DistributeTransaction.Controllers
{
    public class ProductController : BaseController
    {
        private ILog log = LogManager.GetLogger(typeof(ProductController));
        private ProductRepository productRespository;
        private static Dictionary<int, byte[]> ImageCached = new Dictionary<int, byte[]>();

        public ProductController()
        {
            productRespository = new ProductRepository(DBContext);
        }


        //
        // GET: /Product/
        [ActionName("Index")]
        public ActionResult Index(FormCollection formCollection)
        {
            string search = formCollection["SearchString"];
            string condition = string.IsNullOrEmpty(search) ? "%%" : ("%" + search + "%");
            ViewBag.CurrentFilter = search;

            return View(productRespository.GetProducts(condition));
        }

        [ActionName("Image")]
        public FileResult GetImage(int id)
        {
            byte[] imageData;

            lock (ImageCached)
            {
                if (!ImageCached.TryGetValue(id, out imageData))
                {
                    imageData = productRespository.GetImageById(id).Picture;
                    ImageCached.Add(id, imageData);
                }
            }

            if (imageData != null)
            {
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    // 78 is the size of the OLE header for Northwind images
                    ms.Write(imageData, 78, imageData.Length - 78);

                    return File(ms.ToArray(), "image/jpeg");
                }
            }

            return new FileStreamResult(new System.IO.MemoryStream(imageData), "image/jpeg");
        }

        [HttpPost]
        [ActionName("Index")]
        [AcceptSubmitType(Name = "Command", Type = "Add To WatchList")]
        public ActionResult AddToWatchList(FormCollection formCollection)
        {
            IEnumerable<int> productIds = ParseProductIds(formCollection);

            if (User.Identity.IsAuthenticated)
            {
                WatchListRepository watchListRepository = new WatchListRepository(DBContext);
                watchListRepository.UpdateWatchList(productIds, CustomerId);

                ViewBag.Summary = string.Format(
                    CultureInfo.CurrentUICulture,
                    "{0} {1}  been added to Watch List",
                    productIds.Count(),
                    productIds.Count() > 1 ? "items have" : " item has"
                    );
                return Index(formCollection);
            }
            else
            {
                TempData["data"] = string.Join<int>(",", productIds);
                TempData["url"] = "/WatchList";

                return RedirectToAction("Logon", "Account");
            }
        }

        [HttpPost]
        [ActionName("Index")]
        [AcceptSubmitType(Name = "Command", Type = "Add To ShoppingCart")]
        public ActionResult AddToShoppingCar(FormCollection formCollection)
        {
            IEnumerable<int> productIds = ParseProductIds(formCollection);

            if (User.Identity.IsAuthenticated)
            {
                ShoppingCartRepository shoppingCartRepository = new ShoppingCartRepository(DBContext);
                shoppingCartRepository.UpdateShoppingCart(productIds, CustomerId);

                ViewBag.Summary = string.Format(
                    CultureInfo.CurrentUICulture,
                    "{0} {1}  been added to Shopping Cart",
                    productIds.Count(),
                    productIds.Count() > 1 ? "items have" : " item has"
                   );

                return Index(formCollection);
                //return RedirectToAction("Index", "ShoppingCart");
            }
            else
            {
                TempData["data"] = string.Join<int>(",", productIds);
                TempData["url"] = "/ShoppingCart";

                return RedirectToAction("Logon", "Account");
            }
        }
    }
}
